package tasktracker.abstraction.extensions;

import java.util.HashMap;
import java.util.Map;

import tasktracker.abstraction.AbstractTaskTracker;
import tasktracker.abstraction.TaskInfo;
import tasktracker.abstraction.TaskResultInfo;
import tasktracker.abstraction.TaskStatus;

public abstract class ThreadedTaskTracker extends AbstractTaskTracker {

	private Map<String, TaskStatusTracker> statusTrackers = new HashMap<String, TaskStatusTracker>();

	@Override
	public void init() throws Exception {
		// nop
	}

	@Override
	public void startTask(TaskInfo task) throws Exception {
		internalStartTask(task);
	}

	@Override
	public void restoreTask(TaskInfo task) throws Exception {
		internalStartTask(task);
	}

	private void internalStartTask(final TaskInfo task) {
		final String guid = task.getGuid();
		statusTrackers.put(guid, new TaskStatusTracker());
		Thread thread = new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					reportStatus(guid, TaskStatus.RUNNING, null);
					doThreadedTask(task);
				} catch (Exception e) {
					logger.warn("Task[" + guid + "]", e);
					reportStatus(guid, TaskStatus.ERROR, null);
				}
				setCopmletion(guid);
			}
		});
		thread.start();
	}

	protected abstract void doThreadedTask(TaskInfo task) throws Exception;

	@Override
	protected void reportStatus(String guid, int status, TaskResultInfo result) {
		TaskStatusTracker statusTracker = statusTrackers.get(guid);
		if (statusTracker == null)
			return;

		statusTracker.update(status);
		super.reportStatus(guid, status, result);
	}

	private void setCopmletion(String guid) {
		TaskStatusTracker statusTracker = statusTrackers.get(guid);
		if (statusTracker == null)
			return;

		if (!statusTracker.isCompleted()) {
			statusTracker.update(TaskStatus.COMPLETED);
			super.reportStatus(guid, TaskStatus.COMPLETED, null);
		}
	}

	@Override
	public boolean cleanupTask(String guid) throws Exception {
		statusTrackers.remove(guid);
		return false;
	}

}
